package com.rizzo.android.ui;

import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.rizzo.android.R;
import com.rizzo.android.ui.fragment.NavigationListFragment;
import com.rizzo.android.ui.slidingmenu.SlidingMenu;
import com.rizzo.android.ui.slidingmenu.app.SlidingFragmentActivity;

public class BaseActivity extends SlidingFragmentActivity {

    public static final String MENU_SHOWING_STATE = "menuState";

    private int mTitleRes;
    protected NavigationListFragment navigationFragment;

    public BaseActivity(int titleRes) {
        mTitleRes = titleRes;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putBoolean(MENU_SHOWING_STATE, this.getSlidingMenu().isMenuShowing());
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setTitle(mTitleRes);

        // set the Behind View
        setBehindContentView(R.layout.menu_frame);
        FragmentTransaction t = this.getSupportFragmentManager().beginTransaction();
        navigationFragment = new NavigationListFragment();
        t.replace(R.id.menu_frame, navigationFragment);
        t.commit();
        Log.d("BaseActivity", "onCreate fragmentTransaction");

        // customize the SlidingMenu
        SlidingMenu slidingMenu = getSlidingMenu();
        slidingMenu.setShadowWidthRes(R.dimen.shadow_width);
        slidingMenu.setShadowDrawable(R.drawable.shadow);
        slidingMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
        slidingMenu.setFadeDegree(0.45f);
        slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    public void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        boolean menuShowing = savedInstanceState != null && savedInstanceState.getBoolean(MENU_SHOWING_STATE);
        if (menuShowing) {
            getSlidingMenu().toggle();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                toggle();
                return true;
            case R.id.overflow:
                toggle();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getSupportMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    protected NavigationListFragment getNavigationFragment() {
        return navigationFragment;
    }
}
